package com.xy.xylive.aop;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.xy.xylive.api.R;
import com.xy.xylive.common.AESUtil;
import com.xy.xylive.common.HttpStatus;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

@ControllerAdvice
@Slf4j
@Order(3)
public class EncryptResponseAspect implements ResponseBodyAdvice<Object> {
    @Autowired
    private AESUtil aesUtil;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return returnType.hasMethodAnnotation(Encrypt.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
            ServerHttpResponse response) {
        if (body instanceof R) {
            R r = (R) body;
            if (r.getCode() != HttpStatus.SUCCESS) {
                return body;
            }
            if(r.getMsg() != null) {
                r.setMsg(aesUtil.encrypt(r.getMsg()));
            }
            if (r.getData() != null) {
                r.setData(aesUtil.encrypt(JSONUtil.toJsonStr(r.getData())));
            }
            r.setEncrypt(1);
        } else {
            log.warn("响应加密不支持，响应类型：{}", body.getClass().getName());
        }
        return body;
    }   
    
}
